<!--
 * @Descripttion: 
 * @version: 
 * @Author: weni09
 * @Date: 2021-05-13 17:01:49
 * @LastEditors: weni09
 * @LastEditTime: 2021-06-16 22:19:58
 * @FilePath: \icoder-frontend\blog\src\components\LoginAndRegister.vue
-->

<template>
<div class="login-register">
  <div class="login-register-btn" @click="initOpen">{{$t("header.loginIn")}}</div>
  <el-dialog custom-class="log-reg-dialog" 
  :before-close="beforeClose" 
  @close="handleClose"
  :visible="$store.getters.logResDialogVisible" 
  :close-on-click-modal="true"
  width="25rem"
  center>
    <div class="dialog-header" slot="title"><span class="dialog-header-text">{{logRestext}}</span></div>
    <el-form :model="ruleForm" 
    status-icon 
    label-position="left" 
    :rules="rules"
     ref="ruleForm" 
     label-width="70px" 
     :modal-append-to-body="true"
     class="login-register-ruleForm"
     @submit.native.prevent>
      <el-form-item label="账号" prop="username">
        <el-input class="el-input-my" type="email" v-model="ruleForm.username" autocomplete="off" placeholder="只能填写邮箱地址"></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname" v-if="!isLogin">
        <el-input v-model="ruleForm.nickname" autocomplete="off" placeholder="请填写昵称"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input class="el-input-my" type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
      </el-form-item>
  <el-form-item label="确认密码" prop="checkpassword" v-if="!isLogin">
    <el-input type="password" v-model="ruleForm.checkpassword" autocomplete="off"></el-input>
  </el-form-item>
  <!-- <el-form-item v-if="logRestitle=='register'" label="头像上传" class="avatar-form" prop="imageUrl">
  <el-upload
  class="avatar-uploader"
  :action="imgUploadUrl"
  name="avatar"
  :multiple="false"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :on-error="handleAvatarFailed"
  :before-upload="beforeAvatarUpload"
  accept="image/jpeg,image/gif,image/png"
  >
  <img v-if="ruleForm.imageUrl" :src="ruleForm.imageUrl" class="avatar-img">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
  </el-form-item> -->
      <el-form-item label-width="0" class="log-res-btn-item">
        <el-button 
        :type="submitBtnType" 
        @click="submitForm('ruleForm')" 
        native-type="submit"
        :disabled="disabled" 
        :loading="loading"
        class="log-res-btn">{{logRestext}}</el-button>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
    <el-button type="text" class="register-immediately-btn"  @click="toggleLogRes" :disabled="resDisabled">立即注册</el-button>
    </div>
</el-dialog>

  </div>
</template>

<script>
import { loginIn,register } from 'api';
import md5 from 'js-md5';

export default {
    inject:['reload'],
    data(){
        var validatepassword2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
       };
        return {
          isLogin:true,
          ruleForm:{
            username:"",
            nickname:"",
            password:"",
            checkpassword:"",
            // imageUrl: "",
          },
          rules: {
          username: [{required: true,message: '请输入邮箱地址', trigger: 'blur' },
                { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
          nickname:[{required:true,message:"请输入昵称"}],
          password: [{required: true, message:"请输入密码", trigger: 'blur' }],
          checkpassword:[{required: true, validator: validatepassword2, trigger: 'blur' }],
        },
        submitBtnType:"primary",
        disabled: false,
        loading:false,
        imgUploadUrl: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_API : process.env.VUE_APP_API_DEV + "/file/upload",
        resDisabled:false,
        };
    },
    props:{
 
    },
    computed:{
        logRestext:function(){
          if (this.isLogin){
            return this.$t('header.loginIn')
          }
          else{
            return this.$t('header.register')
          }
        }
    },
    
    methods:{
      //打开方法
      initOpen(){
        this.$store.dispatch('setLogResDialog',true);
      },
      handleClose(){
        this.$store.dispatch('setLogResDialog',false);
        this.isLogin = true;
        this.resDisabled=false;
      },
      //关闭之前重置表单，清除检验
     beforeClose(done){
      if(this.$refs.ruleForm){
        this.$refs.ruleForm.resetFields();
        this.$refs.ruleForm.clearValidate();
        done();
      }
     },

    //登录注册提交表单
    submitForm(formName) {
        this.submitting();
        this.$refs[formName].validate((valid) => {
          if (valid) {
          this.ruleForm.password=md5(this.ruleForm.password + 'randompassword')
          if (this.isLogin){
          //请求登录接口
          console.log("loginIn: ",this.ruleForm)
          loginIn(this.ruleForm).then(res => {
            // console.log("statusCode",res.statusCode)
           this.$store.commit('SET_AUTH',res);
           this.handleClose();
           this.loginResult(res.user.username,"success");
           this.reload(); //刷新当前路由
        	}).catch(err => {
            this.loginResult(this.ruleForm.username,"error");
            this.initSubmit();
            console.log(err)
        	});
          }
          else{
          //请求注册接口
          let params = Object.assign({},this.ruleForm)
          delete params.checkpassword;
          // console.log("register: ",params);
          register(params).then(res => {
            this.ruleForm.password="";
            this.ruleForm.checkpassword="";
            this.$refs.ruleForm.clearValidate();
            this.initSubmit();
           if (res.msg=="ERROR_EMAIL_ADDRESS"){
              this.myNotify('error','账号必须是邮箱地址！')
              return
           }
           if (res.msg=="USERNAME_ALREADY_EXISTS"){
              this.myNotify('error','账号已存在！')
              return
           }
           if (res.msg=="NICKNAME_ALREADY_EXISTS"){
              this.myNotify('error','昵称已存在！')
              return
           }
           this.$refs.ruleForm.resetFields();
           this.ruleForm.username = params.username;
           this.loginResult(params.username,"success");
           this.isLogin = true;

        	}).catch(err => {
            this.$refs.ruleForm.resetFields();
            console.log("error: ",err)
            // this.loginResult(params.username,"error");
            this.initSubmit();
           
        	});
          }
          } else {
            this.initSubmit();
            return false;
          }
        });

    },

    //初始化提交状态
    initSubmit:function(){
        this.submitBtnType="primary";
        // this.submitBtnText=this.logRestext;
        this.disabled=false;
        this.loading=false;
    },
    //点击按钮切换提交中状态
    submitting:function(){
        this.submitBtnType = "info";
        // this.submitBtnText = this.logRestext + "...";
        this.disabled = true;
        this.loading = true;

    },
    toggleLogRes:function(){
      if(this.isLogin){
      this.$refs.ruleForm.resetFields();
      this.$refs.ruleForm.clearValidate();
      this.isLogin = !this.isLogin;
      this.resDisabled = true;

      }
    },

    //自定义消息弹出框
    myNotify(state,msg){
      this.$notify({
        position: 'top-left',//左上方显示
        type:state,
        duration:2000, //显示2秒自动消失
        showClose:false, //不显示关闭按钮
        message:msg, //显示的消息
        offset:100, //到顶部的偏移量
      })
    },
    loginResult(username,state){
      if (state=="success"){
        var stateText = "成功"
      }
      else if(state=="error"){
        var stateText = "失败"
      };

      this.myNotify(state,username + " " +  this.logRestext + stateText);
    },
    handleAvatarSuccess(res, file) {
      if (res.data && res.data.url){
        this.ruleForm.imageUrl = res.data.url
        this.myNotify('success','头像上传成功! ');
      }
      else{
        this.myNotify('error','头像上传失败! ' + res.msg);
      }
    },
    handleAvatarFailed(err,file,fileList){
      this.myNotify('error','头像上传失败! ' + err);
    },
    beforeAvatarUpload(file) {
      const imgArr = ['image/jpeg','image/gif','image/png']
      const isJPG =  imgArr.indexOf(file.type) != -1;
      const isLt2M = file.size / 1024  < 500;
      if (!isJPG) {
        this.myNotify('error','上传头像只支持JPEG/GIF/PNG 格式!');
      }
      if (!isLt2M) {
        this.myNotify('error','上传头像图片大小不能超过 500K!');
      }
        return isJPG && isLt2M;
      },
      
   },
  mounted(){
  },

}
</script>

<style lang="scss">
.el-dialog__footer{
  padding: 10px 10px!important;
}
.log-reg-dialog .el-dialog__body{
  padding: 10px 30px 0;
}
.log-res-btn-item{
  margin-bottom: 0px;
  padding-top: 10px;
}

</style>
<style lang="scss" scoped>
@import '@/styles/LoginOrRegister.scss';

</style>